<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :model="queryWhere" :inline="true">
          <el-form-item>
            <el-input v-model="queryWhere.nickname" placeholder="输入歌手昵称进行查询"></el-input>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" @click="initTableData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addSinger">添加歌手</el-button>
          </el-form-item>
        </el-form>
        <el-form>

          <el-button type="danger" icon="el-icon-delete" @click="deleteAll" plain>批量删除</el-button>
        </el-form>





      </el-col>

    </el-row>


    <!-- <el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" -->
    <el-table border ref="multipleTable" v-loading="loading" element-loading-text="玩命加载中"
      element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :data="tableData"
      tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>


      <el-table-column label="歌手头像" prop="avater">
        <template slot-scope="scope">

          <el-image style="width: 100px; height: 100px" :src="scope.row.avater" fit="fill"></el-image>

        </template>

      </el-table-column>

      <el-table-column label="歌手昵称" prop="nickname">
      </el-table-column>

      <el-table-column label="歌手性别" prop="sex" :formatter="formatterSex">
      </el-table-column>
      <el-table-column label="歌手生日" prop="birthday">
      </el-table-column>

      <el-table-column label="歌手描述" prop="description"  width="250">
        <template slot-scope="scope">
          <el-input
            type="textarea"

            :readonly="true"
            placeholder="请输入内容"
            v-model="scope.row.description">
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="歌手地区" prop="localtion">
      </el-table-column>

<!--      </el-table-column>-->

      <el-table-column label="创建时间" prop="createTime">
      </el-table-column>
      <el-table-column label="更新时间" prop="updateTime">
      </el-table-column>

      <el-table-column align="center" label="操作">

        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleEdit(scope)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryWhere.currentPage" :page-sizes="[2,10, 20, 30, 40]" :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalRecord">
    </el-pagination>

    <!-- 编辑界面 -->
    <el-dialog title="信息编辑界面" :visible.sync="dialogVisible" width="1024">
      <el-form :model="singerInfo" :rules="rules" :inline="true" label-width="100px">
        <el-form-item label="歌手性别" prop="sex">
          <el-radio v-model="singerInfo.sex" :label="1">男</el-radio>
          <el-radio v-model="singerInfo.sex" :label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="歌手描述">
          <el-input v-model="singerInfo.description"></el-input>
        </el-form-item>
        <el-form-item label="歌手昵称" prop="nickname">
          <el-input v-model="singerInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="歌手生日" prop="birthday">

          <el-date-picker v-model=" singerInfo.birthday" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="歌手地区">
          <el-input v-model="singerInfo.localtion"></el-input>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload ref="my-upload" action="http://lzyzone.top/uploadimage/image/upload/ly" list-type="text" :limit="1"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
            :on-exceed="handleExceed" :before-upload="beforeAvatarUpload">
            <img v-if="getAvater" :src="getAvater" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- beforeAvatarUpload -->
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" v-show="!isShow" @click="updateSinger">确定修改</el-button>
        <el-button type="primary" v-show="isShow" @click="addSure">确定增加</el-button>
      </div>




    </el-dialog>

  </div>
</template>

<script>
  import {
    formatDate,
    format
  } from '../../api/index.js'
	
	import singer from '../../api/singer.js'

  export default {
    name: "Singer",
    data() {
      return {
        selectValue: [],
        isShow: false, //根据选择展示修改或者添加
        singerInfo: { //用于双向绑定表单的数据
          singerId: "",
          avater: "",
          sex: "",
          description: "",
          nickname: "",
          localtion: "",
          birthday: "",
          isDeleted: "",
          createTime: "",
          updateTime: ""


        },
        rules: {
          nickname: [{
              required: true,
              message: '请输入歌手昵称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 5,
              message: '长度在 2 到 5 个字符',
              trigger: 'blur'
            }
          ],
          birthday: [{
              required: true,
              message: '请输入歌手生日',
              trigger: 'blur'
            }

          ],

        },
        loading: true,
        currentEditsingerInfo: {}, //用于存储当前用户点击修改时的歌手信息

        queryWhere: {
          nickname: "",
          currentPage: 1,
        },
        dialogVisible: false, //用于控制弹出框是显示还是隐藏。
        pageInfo: {
          pageSize: 2,
          totalPage: 0,
          totalRecord: 0,
        },
        tableData: [],
        search: '',

      }
    },
    methods: {


      // 文件上传时的钩子
      handleAvatarSuccess(res, file) {
        console.log('res', res)
        this.singerInfo = {
          ...this.singerInfo
        }
        this.singerInfo.avater = res.data.filePath
      },
      // 文件移除时的钩子
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.singerInfo = {
          ...this.singerInfo
        }
        this.singerInfo.avater = null
      },
      // 点击已 上传文件时的钩子
      handlePictureCardPreview(file) {
        console.log('url', file.url)
        this.singerInfo.avater = file.url;
        this.dialogVisible = true;
      },
      // 文件上传超出限制时的钩子
      handleExceed(files, fileList) {
        this.$message('只能上传一个头像哦!')
      },
      // 处理显示的性别
      formatterSex(rows, column) {
        // 1表示男，0表示女，存储数据库中的类型为int类型0或1
        if (rows.sex != 0 && rows.sex != 1) return '未知'
        return rows.sex == 1 ? "男" : "女";

        return rows.sex == 1 ? "男" : "女";
      },


      beforeAvatarUpload: function (file) {

        //文件上传前对文件的大小和类型做检查
        const isJPG = file.type.indexOf('image') >= 0 ? true : false;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('只能上传图片!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //编辑界面的弹框
      handleEdit(scope) {

        this.singerInfo = {};
        let a = {
          ...scope.row
        }
        this.singerInfo = a;
        console.log(scope.row);
        this.isShow = false;

        for (let attr in scope.row) {
          this.singerInfo[attr] = scope.row[attr]
        }
        console.log("dsa1sd", this.singerInfo);
        this.dialogVisible = true; //显示弹出框

      },
      addSinger() { //添加

        console.log();
        this.singerInfo = {};

        this.isShow = true;
        this.dialogVisible = true; //显示弹出框

        // ,{params:this.singerInfo}
      },
      addSure() { //确定添加
	   this.singerInfo.birthday = formatDate(this.singerInfo.birthday)
        console.log("添加的数据",this.singerInfo)
        let _this = this;
        console.log(this.singerInfo.birthday);
        this.singerInfo.createTime = '2020-01-22 15:30:30';
        this.singerInfo.updateTime = '2021-02-23 15:30:30';
        console.log(this.singerInfo.createTime);


        singer.add(this.singerInfo).then(
          response => {
            this.initTableData();
            this.dialogVisible = false;
            this.$notify({
              message: '增加成功',
              type: 'success'
            });


          },
          error => {
            console.log('请求失败了', error.message)
          }
        )

      },

      //删除歌手
      handleDelete(index, row) {
        console.log(index, row);
        console.log("www" + row.singerId)
        let _this = this;
        this.$confirm('此操作将永久删除该歌手信息, 您确认是否要继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {


          singer.delete(row.singerId).then(
            response => {
              _this.initTableData()

            },
            error => {
              console.log('请求失败了', error.message)
            }
          )

          this.$message({
            type: 'success',
            message: '删除成功!',
          });


        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });




      },

      handleSizeChange(val) {

      },
      handleCurrentChange(curpage) {
        this.loading = true;
        this.queryWhere.currentPage = curpage;
        this.initTableData()

      },

      //查询歌手
      initTableData() {
        let _this = this;
		this.queryWhere.pageSize = this.pageInfo.pageSize
		console.log('aaaa',this.queryWhere)
      singer.queryPage(this.queryWhere).then(
          response => {
            this.loading = true;
            response.data.data.list.forEach(data => {
              data.birthday = format(data.birthday)
              data.createTime = formatDate(data.createTime)
              data.updateTime = formatDate(data.updateTime)
            })


            console.log("请求成功了", response.data)

            console.log(response.data.data.currentPage)
            _this.queryWhere.currentPage = response.data.data.pageNum;
            _this.pageInfo.totalPage = response.data.data.pages;
            _this.pageInfo.totalRecord = response.data.data.total - 0;


            _this.pageInfo.pageSize = response.data.data.pageSize;

            console.log("asd1" + response.data.data.pageSize)
            _this.tableData = response.data.data.list;

            if (this.tableData.length == 0 && this.queryWhere.currentPage !== 1) {
              this.queryWhere.currentPage--
              this.initTableData()
            }
            this.loading = false

          },
          error => {
            console.log('请求失败了', error.message)
          }
        )
      },
      //编辑歌手
      updateSinger() {
        let _this = this;
        this.singerInfo.birthday = formatDate(this.singerInfo.birthday)
        this.singerInfo.createTime = formatDate(this.singerInfo.createTime)
        this.singerInfo.updateTime = formatDate(this.singerInfo.updateTime)
		console.log("sssss",this.singerInfo)
        singer.update(this.singerInfo).then(
          response => {
            this.dialogVisible = false;
            for (let attr in this.singerInfo) {
              _this.currentEditsingerInfo[attr] = _this.singerInfo[attr]
            }

            this.$notify({

              message: '修改成功',
              type: 'success'
            });

            this.initTableData()
          },
          error => {
            console.log('请求失败了', error.message)
          }
        )


      },

      //多选框
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.selectValue = val;
      },
      //批量删除
      deleteAll() {
        console.log("aaaa", this.selectValue);

        let id = []
        this.multipleSelection.forEach(selectValue => {
            id.push(
              selectValue.singerId
            )
          });
		
		  
          

        let _this = this;
        this.$confirm('此操作将永久删除该歌手信息, 您确认是否要继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
			  console.log("我传的id值为",id)
          singer.deleteAll(id).then(
            response => {
				  console.log("我进来了")
              _this.initTableData()
        
            },
            error => {
              console.log('请求失败了', error.message)
            }
          )
          this.$message({
            type: 'success',
            message: '删除成功!',
          });

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },




    },
    computed: {
      getAvater() {
        return this.singerInfo.avater;
      }
    },


    mounted() {
      this.initTableData()
    },

    watch: {
      'singerInfo': {
        handler: (val) => {
          console.log("------");
          this.singerInfo = val;
        }
      }
    }

  }

</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
